<template>
<!-- 手动上传图片组件，待完善-->
  <div :style="{height}">
    <el-upload
      action="#"
      list-type="picture-card"
      :auto-upload="false"
      :file-list="imagesFileList"
      multiple
      :on-change="handleImageChange"
      :limit="3"
      :on-exceed="handleExceed"
      accept=".jpeg,.jpg,.png"
    >
      <i slot="default" class="el-icon-plus"></i>
      <div slot="file" slot-scope="{file}">
        <el-image
          fit="contain"
          :src="file.url"
          :preview-src-list="previewImagesList"
          ref="elImage"
          style="width: 146px; height:146px;"
        >
        </el-image>
        <span class="el-upload-list__item-actions">
          <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
            <i class="el-icon-zoom-in"/>
          </span>
          <span class="el-upload-list__item-delete" @click="handleRemove(file)">
            <i class="el-icon-delete"/>
          </span>
        </span>
      </div>
    </el-upload>
  </div>
</template>

<script>
import axios from "@/utils/request";
import {base64toFile} from "@/utils/imageUrlToFile";
import {commonUpload} from "@/api/monitor/equipmentFault";

export default {
  name: "UploadImages",

  props: {
    height: {
      type: String,
      default: "170px"
    },
    defaultImagesUrl: {
      type: Array,
      default: []
    }

  },

  data() {
    return {
      imagesFileList: [],
      // 正在上传图片提示
      isUploading: false,
      imagesHasChanged: false
    }
  },
  created() {

  },
  methods: {
    // 上传多张图片
    uploadImages(callBack) {
      const uploadReqList = [];

      // 如果清空了图片
      if (!this.imagesFileList.length) {
        this.form.image = '';
        return callBack && callBack();
      }

      for (var i = 0; i < this.imagesFileList.length; i++) {
        let formData = new FormData();
        formData.append("file", this.imagesFileList[i].raw);
        uploadReqList.push(commonUpload(formData))
      }

      Promise.all(uploadReqList).then(res => {
        const urlArray = res.map(item => item.data);
        // 将url拼接传给后端
        this.form.image = urlArray.join(",")
        this.$modal.msgSuccess('图片上传成功！');
        callBack && callBack();
      }).catch(err => {
        this.isUploading = false;
        this.$modal.msgError('图片上传失败，请重新提交');
      })
    },
    // 图片超过3张
    handleExceed() {
      this.$modal.msgWarning("最多只能上传3张图片");
    },
    // 预览大图url数组
    previewImagesList() {
      return this.imagesFileList.map(item => item.url)
    },
    // 上传图片改变
    handleImageChange(file, fileList) {
      this.imagesFileList = fileList;
      // 标记图片修改
      if (!this.imagesHasChanged) this.imagesHasChanged = true;
      // 图片大小不能大于10M
      if (file.raw.size >= 10 * 1024 * 1024) {
        this.$modal.msgWarning("图片大小不能大于10M");
        this.handleRemove(file);
      }

    },
    // 删除图片
    handleRemove(file) {
      // 标记图片修改
      if (!this.imagesHasChanged) this.imagesHasChanged = true;

      // 删除imagesFileList对应file
      this.imagesFileList = this.imagesFileList.filter(item => {
        return item.uid !== file.uid
      })
    },
    // 预览图片
    handlePictureCardPreview() {
      this.$refs.elImage.showViewer = true;
    },
    // 图片url转成文件对象
    urlToFile(url, success, fail) {
      axios.get(url, {responseType: 'blob'})
        .then((blob) => {
          const reader = new FileReader();
          // 转base64
          reader.readAsDataURL(blob);
          reader.onloadend = () => {
            const extName = url.match(/\.(jpg|png|jpeg|gif)$/)[0];
            // 图片文件名
            const fileName = Date.now() + extName;
            const file = base64toFile(reader.result, fileName);
            file.extName = extName;
            success && success({raw: file});
          }
        })
        .catch(() => fail && fail())
    },
  }
}
</script>

<style lang="scss" scoped>

</style>
